<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use support\Db;
use app\model\DiscussModel;

class Discuss extends BaseApi
{
    protected ?string $dataModel = DiscussModel::class;
    protected array $with = [];
    protected array $allowSearch = ['title', 'content', 'status', 'topic_id'];

    //随机获取话题列表
    public function random()
    {
        $list = DiscussModel::inRandomOrder()->limit(6)->get()->toArray();
        return $this->success($list);
    }

    //获取指定话题的讨论列表
    public function getListByTopicId()
    {
        $topicId = input("topic_id");
        $days = input('days', 7); // 默认7天，可配置

        // 参数验证
        if (empty($topicId)) {
            return $this->fail("话题ID不能为空");
        }

        try {
            $list = DiscussModel::with(['user:id,nickname,avatar'])
                ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime("-{$days} days")))
                ->where('topic_id', $topicId)
                ->orderBy('id', 'desc')
                ->paginate(10);

            return $this->dataByPage($list);
        } catch (\Exception $e) {
            return $this->fail("获取话题列表失败");
        }
    }

    //用户创建讨论
    public function userAdd()
    {
        $params = request()->all();

        // 获取用户ID
        $userId = $this->getUserId(true);
        $params["user_id"] = $userId;

        if (empty($params['topic_id'])) {
            return $this->fail("圈子ID不能为空");
        }

        $info = DiscussModel::create($params);
        return $this->success($info);
    }

    public function infoById()
    {
        $id = input("id");

        // 参数验证
        if (empty($id)) {
            return $this->fail("讨论ID不能为空");
        }

        $info = DiscussModel::with(['user:id,nickname,avatar'])->where("id", $id)->first();

        if (!$info) {
            return $this->fail("讨论不存在");
        }

        // 增加浏览次数
        DiscussModel::where('id', $id)->increment('see_num');

        return $this->success($info);
    }
}